package com.android.clinic.app.ui.personal;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.clinic.app.R;
import com.android.clinic.app.base.BaseActivity;
import com.android.clinic.app.entity.DuePriceInfo;
import com.android.clinic.app.http.HttpClient;
import com.android.clinic.app.http.base.BaseObserver;
import com.android.clinic.app.http.utils.RxObservableUtils;
import com.android.clinic.app.ui.doctor.CustomerServiceActivity;
import com.android.clinic.app.ui.pay.ClinicAliPay;
import com.android.clinic.app.ui.pay.ClinicWeChatPay;
import com.android.clinic.app.ui.pay.OnWXPayCallbackListener;
import com.android.clinic.app.ui.pay.PayUtils;
import com.android.clinic.app.ui.widget.dialog.ConfirmOrderDialog;
import com.android.clinic.app.utils.Utils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

/**
 * Created by cheng on 2018/3/14.
 * 购买会员卡
 */
public class BuyMemberCardActivity extends BaseActivity {

    private TextView tvPrice;
    private EditText etName, etAddress, etPhone;
    private ImageView ivWxPay, ivAliPay;

    private String mName, mAddress, mPhone = "";
    private boolean isPayType = true;
    private ConfirmOrderDialog mDialog;

    private String payMoney = "";

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_buy_memeber_card;
    }

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        setTitleBarTitle("购买会员卡");
        setTitleBarLeftResource(R.drawable.icon_back);
        etName = (EditText) findViewById(R.id.et_name);
        etAddress = (EditText) findViewById(R.id.et_address);
        etPhone = (EditText) findViewById(R.id.et_phone);
        tvPrice = (TextView) findViewById(R.id.tv_price);

        ivWxPay = (ImageView) findViewById(R.id.iv_wx_pay);
        ivAliPay = (ImageView) findViewById(R.id.iv_ali_pay);
        ivWxPay.setSelected(isPayType);

        mDialog  = new ConfirmOrderDialog(this);
    }

    @Override
    protected void loadData() {
        super.loadData();
        HttpClient.getHttpService().getDuePrice()
                .compose(RxObservableUtils.applySchedulers())
                .subscribe(new BaseObserver<List<DuePriceInfo>>() {
                    @Override
                    public void onSuccess(List<DuePriceInfo> duePriceInfoList) {
                        DuePriceInfo duePriceInfo = duePriceInfoList.get(0);
                        payMoney = duePriceInfo.getPrice();
                        tvPrice.setText(getString(R.string.real_price, payMoney));
                    }

                    @Override
                    public void onFailure(String message) {

                    }
                });
    }

    @Override
    protected void widgetClick(View v) {
        super.widgetClick(v);
        switch (v.getId()) {// 客服
            case R.id.tv_service:
//                PermissionUtils.applyCallPhone(this, new PermissionUtils.CallBack() {
//                    @Override
//                    public void onGuarantee() {
//                        UIAlertView.callPhoneDialog(BuyMemberCardActivity.this, "客服电话", "4001883525");
//                    }
//
//                    @Override
//                    public void onDeny() {
//
//                    }
//                });
                startActivity(new Intent(this, CustomerServiceActivity.class));
                break;
            // 微信支付
            case R.id.layout_wx_pay:
                isPayType = true;
                ivWxPay.setSelected(true);
                ivAliPay.setSelected(false);
                break;
            // 支付宝支付
            case R.id.layout_ali_pay:
                isPayType = false;
                ivWxPay.setSelected(false);
                ivAliPay.setSelected(true);
                break;
            // 去支付
            case R.id.tv_pay:
                if (checkIsEmptyMemberInfo()) {
                    mDialog.show();
                    mDialog.setOrderInfo(mName, mPhone, mAddress, payMoney);
                    mDialog.setOnCompleteClickListener(() -> addAddress());
                }
                break;
        }
    }

    /**
     * 检查用户输入的信息是否有效
     * @return
     */
    private boolean checkIsEmptyMemberInfo() {
        mName = etName.getText().toString();
        mAddress = etAddress.getText().toString();
        mPhone = etPhone.getText().toString();
        if (Utils.isEmpty(mName)) {
            showToast("姓名不能为空");
            return false;
        } else if (Utils.isEmpty(mAddress)) {
            showToast("收货地址不能为空");
            return false;
        } else if (Utils.isEmpty(mPhone)) {
            showToast("手机号不能为空!");
            return false;
        } else if (!Utils.matchPhone(mPhone)) {
            showToast("请输入正确的手机号!");
            return false;
        }
        return true;
    }

    /**
     * 添加收货信息
     */
    private void addAddress() {
        HttpClient.getHttpService().addAddress(mName, mAddress, mPhone, payMoney,
                isPayType ? "爱帮诊服务费" : "爱帮诊支付",
                isPayType ? "" : "爱帮诊服务费")
                .compose(RxObservableUtils.applySchedulers())
                .subscribe(new BaseObserver<String>() {
                    @Override
                    public void onSuccess(String s) {
                        if (isPayType) {
                            weChatPay(s);
                        } else {
                            aliPay(s);
                        }
                    }

                    @Override
                    public void onFailure(String message) {

                    }
                });
    }

    /**
     * 微信支付
     * @param s
     */
    private void weChatPay(String s) {
        try {
            JSONObject jsonObject = new JSONObject(s);
            JSONObject data = jsonObject.getJSONObject("body");
            ClinicWeChatPay weChatPay = new ClinicWeChatPay(BuyMemberCardActivity.this, data);
            weChatPay.initPay();
            // 微信支付回调
            PayUtils.getInstance().setCallBackListener(new OnWXPayCallbackListener() {
                @Override
                public void onSuccess() {
                    showToast("购卡成功!");
                    startLoginActivity();
                }

                @Override
                public void onFailure(int errCode) {
                    showToast("购卡失败");
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 支付宝支付
     * @param s
     */
    private void aliPay(String s) {
        try {
            JSONObject jsonObject = new JSONObject(s);
            String orderInfo = jsonObject.getString("body");
            ClinicAliPay clinicAliPay = new ClinicAliPay(BuyMemberCardActivity.this);
            clinicAliPay.aliPay(orderInfo);
            //支付宝支付回调
            clinicAliPay.setOnPaySuccessListener(new ClinicAliPay.OnPaySuccessListener() {
                @Override
                public void onSuccess() {
                    showToast("购卡成功");
                    startLoginActivity();
                }

                @Override
                public void onFailure() {
                    showToast("购卡失败");
                    finish();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 去登录
     */
    private void startLoginActivity() {
        startActivity(new Intent(this, LoginActivity.class));
        finish();
    }

}
